<template>
  <div>
    <el-form :model="form" ref="form" name="basic" label-width="80px" autocomplete="off" style="margin-top: 10px;margin-left: 10px;">
      <el-row>
        <el-col :span="6">
          <CompanySelect :compName.sync="form.compName" />
        </el-col>
      </el-row>
    </el-form>

    <div style="margin-right: 15px;">
      <el-upload class="upload-demo" style="float: right;margin-bottom: 5px;" action="" :http-request="handleUpload1"
        :show-file-list="false">
        <el-button type="warning" size="mini">导入</el-button>
        <div slot="tip" class="el-upload__tip"></div>
      </el-upload>
      <el-button type="primary" style="float: right;margin-right: 10px;" size="mini" @click="clickDlTemp">导出</el-button>
      <el-button type="primary" style="float: right;margin-right: 10px;" size="mini" @click="clickAdd">新增</el-button>
      <el-button type="success" style="float: right;margin-bottom: 5px;margin-right: 10px;" size="mini"
        @click="clickQuery">查询</el-button>
    </div>
    <div style="padding: 10px 20px;">
      <el-popover placement="right" title="列筛选" trigger="click" width="420" style="float: left;">
        <el-checkbox-group v-model="checkedColumns" size="mini">
          <el-checkbox v-for="item in checkBoxGroup" :key="item" :label="item" :value="item"></el-checkbox>
        </el-checkbox-group>
        <el-button slot="reference" type="primary" size="small" plain>
          <i class="el-icon-arrow-down el-icon-menu" />列表项展示筛选</el-button>
      </el-popover>

      <el-table :data="tableData" :key="key" style="border: solid 1px #c0c0c0;" row-key="index"
        header-row-class-name="table_header" :header-cell-style="{ borderColor: '#C0C0C0' }"
        :cell-style="{ borderColor: '#C0C0C0' }" border @cell-dblclick="doubleClick" id="out-table"
        :row-class-name="tableRowClassName" show-summary :summary-method="getSummaries">
        <!-- <el-table-column v-for="column,index in columns" :key="index" :prop="column.dataIndex"
        :label="column.title" :align="column.align" :width="column.width">
      </el-table-column> -->
        <el-table-column prop="compName" label="企业名称" align="left" min-width="300px">
        </el-table-column>

        <el-table-column prop="goods1" label="消防水枪" align="center" min-width="100px" v-if="colData[0].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods1"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods2" label="消防水带" align="center" min-width="100px" v-if="colData[1].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods2"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods2 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods3" label="消火栓扳手" align="center" min-width="100px" v-if="colData[2].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods3"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods3 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods4" label="强光照明灯" align="center" min-width="100px">
          <template slot-scope="scope" v-if="colData[3].istrue">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods4"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods4 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods5" label="手电筒" align="center" min-width="100px" v-if="colData[4].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods5"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods5 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods6" label="消防斧" align="center" min-width="100px" v-if="colData[5].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods6"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods6 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods7" label="头戴式照明灯" align="center" min-width="100px" v-if="colData[6].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods7"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods7 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods8" label="消防服（套）" align="center" min-width="100px" v-if="colData[7].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods8"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods8 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods9" label="防毒面具" align="center" min-width="100px" v-if="colData[8].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods9"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods9 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods10" label="正压式消防空气呼吸器" align="center" min-width="100px" v-if="colData[9].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods10"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods10 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods11" label="推车式灭火器" align="center" min-width="100px" v-if="colData[10].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods11"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods11 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods12" label="手提式灭火器" align="center" min-width="100px" v-if="colData[11].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods12"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods12 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods13" label="化学防护服" align="center" min-width="100px" v-if="colData[12].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods13"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods13 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods14" label="防化靴" align="center" min-width="100px" v-if="colData[13].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods14"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods14 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods15" label="气体浓度检测仪" align="center" min-width="100px" v-if="colData[14].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods15"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods15 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods16" label="吸附材料或堵漏器材" align="center" min-width="100px" v-if="colData[15].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods16"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods16 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods17" label="担架" align="center" min-width="100px" v-if="colData[16].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods17"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods17 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods18" label="急救箱" align="center" min-width="100px" v-if="colData[17].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods18"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods18 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods19" label="氧气袋" align="center" min-width="100px" v-if="colData[18].istrue">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable v-model="scope.row.goods19"
              @keyup.enter.native="blurInput" @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.goods19 }}</span>
          </template>
        </el-table-column>

        <!-- <el-table-column label="操作" width="380">
        <template slot-scope="scope">
          <el-button size="mini" @click="clickShowEdit(scope.$index, scope.row)">编辑</el-button>

          <el-button size="mini" type="danger"
            @click="clickDel(scope.$index, scope.row)">删除</el-button>

        </template>
      </el-table-column> -->
      </el-table>

    </div>
    <el-pagination background layout="prev, pager, next" :total="total_size" :page-size="100" :current-page="page_no">
    </el-pagination>

    <UpdateModal ref="UpdateModalRef" :clickQuery="clickQuery" :saveFun="updateEmergGoods" :addFun="addEmergGoods" />

    <el-dialog title="删除提示" :visible.sync="delVisible" width="30%">
      <span>确定删除吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import UpdateModal from './updateModal';
  import {
    queryEmergGoodsList,
    updateEmergGoods,
    addEmergGoods,
    delEmergGoods,
    importExcel,
  } from '@/service/emergGoods';
  import columns from './table';
  import FileSaver from 'file-saver';
  import * as XLSX from 'xlsx';
  import CompanySelect from '@/components/CompanySelect';

  // import { tableMixin } from '@/mixin/table';

  export default {
    components: { UpdateModal,CompanySelect },
    // mixins: [tableMixin],

    data() {
      return {
        data: [],
        key: Math.random(),
        pagination: {
          showLessItems: true,
          showQuickJumper: true,
          showSizeChanger: true,
        },
        query: {},
        columns: columns,
        currItem: {},
        page_no: 0,
        page_size: 100,
        form: {},
        tableLoading: false,
        tableData: [],
        total_size: 0,
        loading: false,
        updateEmergGoods,
        addEmergGoods,
        queryEmergGoodsList,
        delVisible: false,
        colTable: 'emergGoodsTables',
        checkBoxGroup: [],
        checkedColumns: [],
        colData: [
          { title: '消防水枪', istrue: true },
          { title: '消防水带', istrue: true },
          { title: '消火栓扳手', istrue: true },
          { title: '强光照明灯', istrue: true },
          { title: '手电筒', istrue: true },
          { title: '消防斧', istrue: true },
          { title: '头戴式照明灯', istrue: true },
          { title: '消防服（套）', istrue: true },
          { title: '防毒面具', istrue: true },
          { title: '正压式消防空气呼吸器', istrue: true },
          { title: '推车式灭火器', istrue: true },
          { title: '手提式灭火器', istrue: true },
          { title: '化学防护服', istrue: true },
          { title: '防化靴', istrue: true },
          { title: '气体浓度检测仪', istrue: true },
          { title: '吸附材料或堵漏器材', istrue: true },
          { title: '担架', istrue: true },
          { title: '急救箱', istrue: true },
          { title: '氧气袋', istrue: true },
        ],
      };
    },
    // 监控列隐藏
    watch: {
      checkedColumns(val, value) {
        let arr = this.checkBoxGroup.filter((i) => !val.includes(i)); // 未选中
        sessionStorage.setItem(this.colTable, JSON.stringify(arr));
        this.colData.filter((i) => {
          if (arr.indexOf(i.title) != -1) {
            i.istrue = false;
          } else {
            i.istrue = true;
          }
        });
      },
    },
    created() {
      // 列筛选
      this.colData.forEach((item, index) => {
        this.checkBoxGroup.push(item.title);
        this.checkedColumns.push(item.title);
      });

      console.log('this.checkBoxGroup', this.checkBoxGroup);
      this.checkedColumns = this.checkedColumns;
      let UnData = sessionStorage.getItem(this.colTable);
      UnData = JSON.parse(UnData);
      if (UnData != null) {
        this.checkedColumns = this.checkedColumns.filter((item) => {
          return !UnData.includes(item);
        });
      }
    },

    methods: {
      clickShowEdit(index, record) {
        this.$refs.UpdateModalRef.openEditDialog({ ...record });
      },
      clickAdd(record) {
        this.$refs.UpdateModalRef.openAddDialog();
      },
      clickDel(index, row) {
        this.delVisible = true;
        this.currItem = { ...row };
      },
      tableRowClassName({ row, rowIndex }) {
        if (row['isHouseOwner'] === 'Y') {
          console.log('warn');
          return 'warning-row';
        }
        return '';
      },
      // 合计行 方法
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          // 这里添加需要进行合计的列的名称
          const sumColArr = ['金额', '特价'];
          if (column.label != '企业名称') {
            const values = data.map((item) => Number(item[column.property]));
            if (!values.every((value) => isNaN(value))) {
              sums[index] = values
                .reduce((prev, curr) => {
                  const value = Number(curr);
                  if (!isNaN(value)) {
                    return prev + curr;
                  } else {
                    return prev;
                  }
                }, 0)
                .toFixed(0); // 固定两位小数
              sums[index] += ''; // 这里可以添加单位 如： sums[index] += '元'
            } else {
              sums[index] = ' ';
            }
          }
        });
        return sums;
      },

      clickDlTemp(index, row) {
        console.log('XLSX', XLSX, document.querySelector('#out-table'));
        var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'));
        var wbout = XLSX.write(wb, {
          bookType: 'xlsx',
          bookSST: true,
          type: 'array',
        });
        try {
          const date = new Date();
          let dateStr =
            date.getFullYear() +
            '-' +
            (date.getMonth() + 1) +
            '-' +
            date.getDate();
          FileSaver.saveAs(
            new Blob([wbout], {
              type: 'application/octet-stream',
            }),
            '应急物资-' + dateStr + '.xlsx'
          );
        } catch (e) {
          if (typeof console !== 'undefined') console.log(e, wbout);
        }
        return wbout;
      },

      blurInput(e) {
        e.target.blur()
      },
      doubleClick(row, column) {
        // 避免点击过快导致多个输入框处于焦点状态
        row[column.property + 'Show'] = false;
        // 避免点击其他单元格导致表格刷新

        console.log('column.property', column.property);
        if (column.property.indexOf('good') < 0) return;
        row[column.property + 'Show'] = true;
        this.key = Math.random();
        console.log('row', row);
        // this.updateTable(row);
      },
      //输入框失焦事件
      onBlur(row, column) {
        row[column.property + 'Show'] = false;
        this.updateTable(row);

        // 请求后台更改数据
      },
      async saveData(row) {
        const res = await updateEmergGoods(row);
        if (res.success) {
          this.$message.success('保存成功');
        } else {
          this.$message.error('保存失败');
        }
        this.clickQuery();
      },

      updateTable(row) {
        this.saveData(row);
      },

      getFD(fileObj) {
        const formData = new FormData();
        formData.append('file', fileObj.file);
        return formData;
      },
      async handleUpload1(fileObj) {
        const fd = this.getFD(fileObj);
        let res = await importExcel(fd);
        if (res.success) {
          this.clickQuery();
        }
        return false;
      },

      async handleDelete() {
        this.delVisible = false;
        const res = await delEmergGoods({
          ...this.currItem,
        });
        if (res.success) {
          this.clickQuery();
        } else {
        }
      },

      async clickQuery() {
        this.loading = true;
        const data = await queryEmergGoodsList({
          ...this.form,
          page_no: this.page_no,
          page_size: this.page_size,
        });
        if (data.success) {
          this.total_size = data.total;
          this.tableData = data.dataList;
        } else {
          this.total_size = 0;
          this.tableData = [];
        }
        this.loading = false;
      },

      // updateEmergGoods(){

      // }
    },

    mounted() {
      console.log('ff:' + this.tableData);
      console.log('ff11:' + this.clickQuery);

      this.clickQuery(queryEmergGoodsList);
    },
  };
</script>
<style scoped>
  /deep/ .table_header th {
    background-color: #e3e3e3 !important;
    height: 40px;
  }

  ::v-deep .el-table .el-table__cell {
    padding: 4px 0px;
  }

  ::v-deep .el-table .warning-row {
    color: red;
  }

  ::v-deep .el-table {
    display: flex;
    flex-direction: column;
  }

  /* order默认值为0，只需将表体order置为1即可移到最后，这样合计行就上移到表体上方 */
  ::v-deep .el-table__body-wrapper {
    order: 1;
  }

  ::v-deep .el-table__fixed-body-wrapper {
    top: 96px !important;
  }

  ::v-deep .el-table__fixed-footer-wrapper {
    z-index: 0;
  }
</style>